<template>
	<div class="bgc-default pad-20 category-table">
		<div class="bg-color-white pad-20">
			<!-- 操作区域 -->
			<div class="mar-b-20">
				<div>
					<el-button @click="doAdd(1)" type="primary">新增一级分类</el-button>
					<el-button @click="openCategoryTemplate" type="primary">分类模板</el-button>
					<el-button @click="handleExpand">全部展开</el-button>
				</div>
			</div>
			<!-- @row-click="rowClick" -->
			<el-table :data="dataList" ref="theTable" row-key="enterpriseCategoryId" :default-expand-all="isExpand"
				:tree-props="{hasChildren: 'hasChildren'}" lazy :load="load" v-loading="listLoading">
				<el-table-column width="200px" label="分类序号">
					<template slot-scope="scope">
						<span :class="'cate-spance-' + scope.row.categoryLevel"></span>
						<span>{{ scope.row.categoryNumber }}</span>
					</template>
				</el-table-column>
				<el-table-column width="480px" label="分类名称">
					<template slot-scope="scope">
						<template v-if="scope.row.enterpriseCategoryId">
							<img v-if="scope.row.categoryImage" :src="scope.row.categoryImage"
								class="width-16 height-16 cat-line" border="0px">
							<span @click="doEdit(scope.row)"
								class="cursor-p cat-line cat-name">{{ scope.row.categoryName }}</span>
						</template>
					</template>
				</el-table-column>
				<el-table-column width="280px" label="分类别名">
					<template slot-scope="scope">
						<span :class="'cate-spance-' + scope.row.categoryLevel"></span>
						<span>{{ scope.row.aliasName }}</span>
					</template>
				</el-table-column>
				<el-table-column label="商品数">
					<template slot-scope="scope">
						<span :class="'cate-spance-' + scope.row.categoryLevel"></span>
						<span>{{ scope.row.goodsCount }}</span>
					</template>
				</el-table-column>
				<el-table-column label="平台分类">
					<template slot-scope="scope">
						<span :class="'cate-spance-' + scope.row.categoryLevel"></span>
						<span v-if="scope.row.quickCategoryId">【快手】: {{ scope.row.quickName }}</span>
						<span :class="'cate-spance-' + scope.row.categoryLevel"></span>
						<span v-if="scope.row.supplyAllianceCategoryId">【供货联盟】:
							{{ scope.row.supplyAllianceCategoryName }}</span>
					</template>
				</el-table-column>
				<el-table-column label="状态">
					<template slot-scope="scope">
						<span :class="'cate-spance-' + scope.row.categoryLevel"></span>
						<span>{{ scope.row.showFlag == 1 ? '显示' : '隐藏' }}</span>
					</template>
				</el-table-column>
				<el-table-column min-width="150px" label="操作" align="right" fixed="right">
					<template slot-scope="scope">
						<template v-if="scope.row.enterpriseCategoryId">
							<el-button v-if="scope.row.categoryLevel == 1" type="text" size="medium"
								@click="doAdd(2, scope.row.enterpriseCategoryId)">新增二级分类</el-button>
							<el-button v-if="scope.row.categoryLevel == 2" type="text" size="medium"
								@click="doAdd(3, scope.row.enterpriseCategoryId)">新增三级分类</el-button>
							<el-button type="text" size="medium" @click="openPlatformThird(scope.row)"
								v-if="platformAuthorityFlag">
								关联平台分类</el-button>
							<el-button type="text" size="medium" @click="doEdit(scope.row)">编辑</el-button>
							<el-button type="text" size="medium" v-if="scope.row.parentId == 0"
								@click="openPoster(scope.row)">广告图设置
							</el-button>
							<el-button v-if="scope.row.categoryLevel == 1" type="text" size="medium"
								@click="opGoodsConfigVisible(scope.row.enterpriseCategoryId,1)">商品参数</el-button>
						</template>
						<el-popconfirm title="您确定删除吗？" @onConfirm="doRemove(scope.row)">
							<el-button type="text" size="medium" slot="reference" class="mar-l-5">删除</el-button>
						</el-popconfirm>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<!-- 新增/编辑分类 -->
		<el-dialog :title="categoryDialogTitle" :visible.sync="categoryVisible" width="480px" append-to-body>
			<el-form :model="categoryForm" ref="categoryForm" label-width="150px" :rules="rules">
				<el-form-item label="分类序号：" prop="categoryNumber">
					<el-input v-model="categoryForm.categoryNumber" style="width: 250px;" maxlength="10"
						@keyup.native="categoryForm.categoryNumber = checkInputPositiveNum(categoryForm.categoryNumber)">
					</el-input>
				</el-form-item>
				<el-form-item label="分类名称：" prop="categoryName">
					<el-input v-model="categoryForm.categoryName" class="width-250"></el-input>
				</el-form-item>
				<el-form-item label="分类别名：">
					<el-input v-model="categoryForm.aliasName" class="width-250"></el-input>
				</el-form-item>
				<el-form-item label="分类图片：">
					<el-upload list-type="picture-card" class="width-150" action="/api/common/uploadFiles"
						accept="image/jpeg,image/gif,image/png,image/bmp" name="files" :data="token"
						:show-file-list="false" v-loading="fileLoading" :on-success="(res)=> handleUploadSuccess(res)"
						:before-upload="beforeUpload">
						<img v-if="categoryForm.categoryImage" :src="categoryForm.categoryImage"
							style="width: 145px; height: 145px">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>
				<el-form-item label="状态：">
					<el-radio-group v-model="categoryForm.showFlag">
						<el-radio :label="1">显示</el-radio>
						<el-radio :label="0">隐藏</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="categoryVisible = false">取消</el-button>
				<el-button type="primary" @click="doSaveCategory">确定</el-button>
			</div>
		</el-dialog>

		<!-- 关联平台分类 -->
		<el-dialog title="" :visible.sync="platformThirdVisible" width="480px" append-to-body>
			<el-form :model="categoryForm" label-width="150px">
				<el-form-item label="分类名称：">
					<el-col :span="16">
						{{ categoryForm.categoryName }}
					</el-col>
				</el-form-item>
				<el-form-item label="供货联盟：">
					<el-col :span="16">
						<el-select v-model="categoryForm.supplyAllianceCategoryId" placeholder="请选择">
							<el-option v-for="(item, index) in supplyAllianceCategoryList" :key="index"
								:label="item.categoryName" :value="item.categoryId">
							</el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<el-form-item label="快手分类：">
					<el-col :span="16">
						<el-select v-model="categoryForm.quickCategoryId" placeholder="请选择">
							<el-option v-for="(item, index) in kuaiShouCategoryList" :key="index"
								:label="item.categoryName" :value="item.platformCategoryId">
							</el-option>
						</el-select>
					</el-col>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="platformThirdVisible = false">取消</el-button>
				<el-button type="primary" @click="doSaveThirdCategory">确定</el-button>
			</div>
		</el-dialog>

		<!--广告图设置-->
		<el-dialog title="广告图设置" :visible.sync="posterVisible" width="550px" append-to-body>
			<category-link :showFlag="posterVisible" :categoryObj="categoryObj" @close="doColoseCategoryLink">
			</category-link>
		</el-dialog>

		<!-- 分类模板 -->
		<el-dialog title="选择分类模板" :visible.sync="catTemplateVisible" width="1200px" append-to-body>
			<category-template :showFlag="catTemplateVisible" @close="doCloseCategoryTemplate"></category-template>
		</el-dialog>

		<!-- 商品参数 -->
		<el-dialog title="设置" :visible.sync="goodsConfigVisible" v-if="goodsConfigVisible" style="height: 800px;"
			@close="closeCpToast()">
			<template>
				<el-tabs v-model="activeType" @tab-click="handleClick">
					<el-tab-pane label="设置商品参数" name="1">
						<template>
							<div class="pad-10 mar-l-24 mar-r-24">
								<el-button @click="addRow(propertyPropList,1)" type="primary">添加属性</el-button>
							</div>
							<el-table :data="propertyPropList" style="width: 100%;padding: 24px;">
								<el-table-column align="center" prop="propertyName" label="属性名称">
									<template slot-scope="scope">
										<el-input v-if="scope.row.isEdit" v-model="scope.row.propertyName"></el-input>
										<div v-if="!scope.row.isEdit">{{scope.row.propertyName}}</div>
									</template>
								</el-table-column>
								<el-table-column align="center" prop="propertyValue" label="属性值">
									<template slot-scope="scope">
										<el-input v-if="scope.row.isEdit" v-model="scope.row.propertyValue"></el-input>
										<div v-if="!scope.row.isEdit">{{scope.row.propertyValue}}</div>
									</template>
								</el-table-column>
								<el-table-column align="center" prop="distance" label="操作">
									<template slot-scope="scope">
										<el-button type="text" @click="scope.row.isEdit = true">编辑</el-button>
										<el-button type="text" @click="deleteRow(scope.$index, propertyPropList)"
											size="small"> 删除 </el-button>
									</template>
								</el-table-column>
							</el-table>
							<div class="dialog-footer">
								<el-button type="primary" @click="doSaveBatchProperty(propertyPropList)">保存</el-button>
								<el-button @click="closeCpToast()">取 消</el-button>
							</div>
						</template>
					</el-tab-pane>
					<el-tab-pane label="设置保障值" name="2">
						<template>
							<div class="pad-10 mar-l-24 mar-r-24">
								<el-button @click="addRow(propertySafeguardList,2)" type="primary">添加保障值</el-button>
							</div>
							<el-table :data="propertySafeguardList" style="width: 100%;padding: 24px;">
								<el-table-column align="center" prop="propertyName" label="保障名称">
									<template slot-scope="scope">
										<el-input v-if="scope.row.isEdit" v-model="scope.row.propertyName"></el-input>
										<div v-if="!scope.row.isEdit">{{scope.row.propertyName}}</div>
									</template>
								</el-table-column>
								<el-table-column align="center" prop="propertyValue" label="保障值">
									<template slot-scope="scope">
										<el-input v-if="scope.row.isEdit" v-model="scope.row.propertyValue"></el-input>
										<div v-if="!scope.row.isEdit">{{scope.row.propertyValue}}</div>
									</template>
								</el-table-column>
								<el-table-column align="center" prop="distance" label="操作">
									<template slot-scope="scope">
										<el-button type="text" @click="scope.row.isEdit = true">编辑</el-button>
										<el-button type="text" @click="deleteRow(scope.$index, propertySafeguardList)"
											size="small"> 删除 </el-button>
									</template>
								</el-table-column>
							</el-table>
							<div class="dialog-footer">
								<el-button type="primary" @click="doSaveBatchProperty(propertySafeguardList)">保存
								</el-button>
								<el-button @click="closeCpToast()">取 消</el-button>
							</div>
						</template>

					</el-tab-pane>
				</el-tabs>
			</template>

		</el-dialog>
	</div>
</template>

<script>
	import {
	  getNameByPath
	} from '@/utils/get-name-by-path'
	import {
	  getCategory,
	  listCategoryByParentId,
	  listThirdCategory,
	  saveEnterpriseCategory,
	  deleteEnterpriseCategory,
	  pageGetPropertyList,
	  saveBatchProperty
	} from '@/api/goods/enterpriseGoodsCategory'
	import {
	  listProjectCategory
	} from '@/api/project/projectGoodsCategory'
	import {
	  getToken
	} from '@/utils/auth'
	import categoryTemplate from './components/category-template'
	import categoryLink from './components/category-link'

	export default {
	  name: getNameByPath(),
	  components: {
	    categoryTemplate,
	    categoryLink
	  },
	  data() {
	    return {
	      isExpand: false,
	      chineseLevelMap: {
	        1: '一',
	        2: '二',
	        3: '三'
	      },
	      // 分类表单
	      categoryForm: {
	        enterpriseCategoryId: '',
	        categoryName: '',
	        parentId: '',
	        aliasName: '',
	        categoryImage: '',
	        categoryLevel: '',
	        categoryNumber: '',
	        showFlag: 1
	      },
	      token: '',
	      fileLoading: false,
	      listLoading: true,
	      // 快手分类集合
	      kuaiShouCategoryList: [],
	      // 供货联盟分类集合
	      supplyAllianceCategoryList: [],
	      // 企业商品分类集合
	      dataList: [],
	      // 分类dialog标题
	      categoryDialogTitle: '',
	      // 分类visible
	      categoryVisible: false,
	      // 平台分类visible
	      platformThirdVisible: false,
	      // 广告visible
	      posterVisible: false,
	      // 分类模板visible
	      catTemplateVisible: false,
	      // 平台对接权限flag
	      platformAuthorityFlag: false,
	      // 商品参数
	      goodsConfigVisible: false,
	      goodsConfigInnerVisible: false,
	      isShowGoodsConfig: true,
	      activeType: '1',
	      propertyPropList: [],
	      propertySafeguardList: [],
	      deleteProjectPropertyDTOList: [],
	      isEdit: false,
	      categoryId: '',
	      // 选中行
	      selectedRow: null,
	      // 广告图参数
	      categoryObj: {},
	      // 表单校验
	      rules: {
	        categoryName: [{
	          required: true,
	          message: '请输入分类名称',
	          trigger: 'blur'
	        }]
	      }
	    }
	  },
	  // 初始化页面
	  created() {
	    this.token = {
	      accessToken: getToken()
	    }
	    this.platformAuthorityFlag = this.getEnterpriseConfig().platformAuthority === 1
	    this.initList()
	  },
	  methods: {
	    // 是否展开table(展开与折叠切换)
	    handleExpand() {
	      this.isExpand = !this.isExpand
	      this.$nextTick(() => {
	        this.forArr(this.dataList, this.isExpand)
	      })
	    },
	    // 遍历
	    forArr(arr, isExpand) {
	      arr.forEach(i => {
	        // toggleRowExpansion(i, isExpand)用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
	        this.$refs.theTable.toggleRowExpansion(i, isExpand)
	        if (i.children) {
	          this.forArr(i.children, isExpand)
	        }
	      })
	    },
	    // 初始化企业商品分类
	    initList() {
	      this.listLoading = true
	      this.dataList = []
	      listCategoryByParentId(this.getEnterpriseId(), null).then(response => {
	        this.dataList = response.data
	        this.listLoading = false
	      })
	    },
	    // 树加载事件
	    load(tree, treeNode, resolve) {
	      listCategoryByParentId(tree.enterpriseId, tree.enterpriseCategoryId).then(response => {
	        resolve(response.data)
	      })
	    },
	    // 文件上传前校验
	    beforeUpload(file) {
	      const isJPG = file.type === 'image/jpeg'
	      const isGIF = file.type === 'image/gif'
	      const isPNG = file.type === 'image/png'
	      const isBMP = file.type === 'image/bmp'
	      if (!isJPG && !isGIF && !isPNG && !isBMP) {
	        this.$message.error('上传图片必须是JPG/GIF/PNG/BMP 格式!')
	      }
	      this.fileLoading = true
	      return (isJPG || isBMP || isGIF || isPNG)
	    },
	    // 图片上传事件
	    handleUploadSuccess(res) {
	      this.fileLoading = false
	      if (res.code === 101) {
	        this.categoryForm.categoryImage = res.data[0]
	      } else {
	        this.$message({
	          type: 'error',
	          message: res.msg
	        })
	      }
	    },
	    // 获取第三方分类
	    listThirdCategory(enterpriseCategoryId) {
	      this.kuaiShouCategoryList = []
	      listThirdCategory(enterpriseCategoryId).then(response => {
	        if (response.isError) return
	        this.kuaiShouCategoryList = response.data.kuaiShouCategoryList
	      })
	    },
	    // 获取供应联盟分类
	    listProjectCategory(enterpriseCategoryId) {
	      this.SupplyAllianceCategoryList = []
	      listProjectCategory(enterpriseCategoryId).then(response => {
	        if (response.isError) return
	        this.supplyAllianceCategoryList = response.data.supplyAllianceCategoryList
	      })
	    },
	    // 设置分类表单数据
	    setCategoryForm(obj) {
	      this.categoryForm = {
	        enterpriseId: obj.enterpriseId,
	        enterpriseCategoryId: obj.enterpriseCategoryId,
	        parentId: obj.parentId,
	        categoryLevel: obj.categoryLevel,
	        categoryName: obj.categoryName,
	        aliasName: obj.aliasName,
	        categoryImage: obj.categoryImage,
	        quickCategoryId: obj.quickCategoryId,
	        supplyAllianceCategoryId: obj.supplyAllianceCategoryId,
	        categoryNumber: obj.categoryNumber,
	        showFlag: obj.showFlag
	      }
	    },
	    // 新增事件
	    doAdd(level, parentId) {
	      const obj = {
	        enterpriseId: this.getEnterpriseId(),
	        parentId: parentId,
	        categoryLevel: level,
	        showFlag: 1
	      }
	      this.selectedRow = null
	      this.setCategoryForm(obj)
	      this.categoryDialogTitle = '新增' + this.chineseLevelMap[level] + '级分类'
	      this.categoryVisible = true
	    },
	    // 编辑事件
	    doEdit(row) {
	      this.selectedRow = row
	      this.setCategoryForm(row)
	      this.categoryDialogTitle = '编辑分类'
	      this.categoryVisible = true
	    },
	    // 明细行删除事件
	    doRemove(row) {
	      this.listLoading = true
	      deleteEnterpriseCategory(row.enterpriseCategoryId).then((response) => {
	        if (response.isError) {
	          this.listLoading = false
	          return
	        }
	        this.$message({
	          type: 'success',
	          message: '删除成功'
	        })
	        this.initList()
	      })
	    },
	    // 分类保存事件
	    doSaveCategory() {
	      this.$refs['categoryForm'].validate((valid) => {
	        if (valid) {
	          saveEnterpriseCategory(this.categoryForm).then(response => {
	            if (response.isError) return
	            this.categoryVisible = false
	            this.$message({
	              type: 'success',
	              message: '保存成功'
	            })
	            // this.initList()
	            if (this.selectedRow) {
	              this.$set(this.selectedRow, 'categoryName', this.categoryForm.categoryName)
	              this.$set(this.selectedRow, 'categoryImage', this.categoryForm
	                .categoryImage)
	              this.$set(this.selectedRow, 'aliasName', this.categoryForm.aliasName)
	              this.$set(this.selectedRow, 'categoryNumber', this.categoryForm
	                .categoryNumber)
	              this.$set(this.selectedRow, 'showFlag', this.categoryForm.showFlag)
	            } else {
	              this.initList()
	            }
	          })
	        }
	      })
	    },
	    // 打开关联第三方分类事件

	    openPlatformThird(row) {
	      // 查询
	      this.listThirdCategory(row.enterpriseCategoryId)
	      this.listProjectCategory(row.enterpriseCategoryId)
	      this.selectedRow = row
	      this.setCategoryForm(row)
	      this.platformThirdVisible = true
	    },
	    // 平台分类保存事件
	    doSaveThirdCategory() {
	      this.listLoading = true
	      saveEnterpriseCategory(this.categoryForm).then(response => {
	        if (response.isError) return
	        getCategory({
	          enterpriseCategoryId: this.categoryForm.enterpriseCategoryId
	        }).then(response => {
	          const data = response.data
	          this.$set(this.selectedRow, 'quickCategoryId', data.quickCategoryId)
	          this.$set(this.selectedRow, 'quickName', data.quickName)
	          this.$set(this.selectedRow, 'supplyAllianceCategoryId', data
	            .supplyAllianceCategoryId)
	          this.$set(this.selectedRow, 'supplyAllianceCategoryName', data
	            .supplyAllianceCategoryName)
	          this.listLoading = false
	          this.platformThirdVisible = false
	        })
	      })
	    },
	    // 分类模板dialog打开事件
	    openCategoryTemplate() {
	      this.catTemplateVisible = true
	    },
	    // 分类模板dialog关闭事件
	    doCloseCategoryTemplate() {
	      this.catTemplateVisible = false
	    },
	    // 打开广告事件
	    openPoster(row) {
	      this.selectedRow = row
	      this.categoryObj = {
	        enterpriseCategoryId: row.enterpriseCategoryId,
	        posterUrl: row.posterUrl,
	        linkType: row.linkType,
	        linkRemark: row.linkRemark
	      }
	      this.posterVisible = true
	    },
	    // 广告设置dialog关闭事件
	    doColoseCategoryLink(enterpriseCategoryId) {
	      if (enterpriseCategoryId) {
	        getCategory({
	          enterpriseCategoryId: enterpriseCategoryId
	        }).then(response => {
	          const data = response.data
	          this.selectedRow.linkType = data.linkType
	          this.selectedRow.posterUrl = data.posterUrl
	          this.selectedRow.linkRemark = data.linkRemark
	          this.posterVisible = false
	        })
	      } else {
	        this.posterVisible = false
	      }
	    },
	    // 打开商品分类属性参数
	    opGoodsConfigVisible(enterpriseCategoryId, propertyType) {
	      this.propertyPropList = []
	      this.propertySafeguardList = []
	      this.categoryId = enterpriseCategoryId
	      this.activeType = '1'
	      this.goodsConfigVisible = true
	      this.getPageGetPropertyList(enterpriseCategoryId, propertyType)
	    },
	    // 获取商品分类属性参数
	    getPageGetPropertyList(enterpriseCategoryId, propertyType) {
	      pageGetPropertyList({
	        categoryId: enterpriseCategoryId,
	        propertyType: propertyType
	      }).then(response => {
	        if (response.isError) return
	        if (propertyType === 1) {
	          this.propertyPropList = response.data.records
	        }
	        if (propertyType === 2) {
	          this.propertySafeguardList = response.data.records
	        }
	      })
	    },
	    handleClick() {
	      if (this.activeType === '1') {
	        if (this.propertyPropList.length === 0) {
	          this.getPageGetPropertyList(this.categoryId, 1)
	        }
	      }
	      if (this.activeType === '2') {
	        if (this.propertySafeguardList.length === 0) {
	          this.getPageGetPropertyList(this.categoryId, 2)
	        }
	      }
	    },
	    addRow(tableData, propertyType) {
	      tableData.push({
	        propertyName: '',
	        propertyValue: '',
	        categoryId: this.categoryId,
	        propertyType: propertyType,
	        isEdit: true
	      })
	    },
	    deleteRow(index, rows) { // 删除改行
	      this.deleteProjectPropertyDTOList.push(rows[index])
	      rows.splice(index, 1)
	    },
	    doSaveBatchProperty(row) {
	      var property = []
	      property = property.concat(this.propertyPropList)
	      property = property.concat(this.propertySafeguardList)
	      const param = {
	        projectPropertyDTOList: property,
	        deleteProjectPropertyDTOList: this.deleteProjectPropertyDTOList
	      }
	      saveBatchProperty(param).then(response => {
	        if (response.isError) return
	        this.$message({
	          type: 'success',
	          message: '保存成功!'
	        })
	        setTimeout(() => {
	          this.goodsConfigVisible = false
	        }, 1000)
	      })
	    },
	    closeCpToast() {
	      this.propertyPropList = []
	      this.propertySafeguardList = []
	      this.categoryId = ''
	      this.goodsConfigVisible = false
	    }
	  }

	}
</script>

<style lang="less" scoped>
	/deep/ .el-table__expand-icon {
		.el-icon-arrow-right {
			color: #409eff;
		}
	}

	.cat-name {
		color: #155bd4;
	}

	.cate-spance-2 {
		display: inline-block;
		width: 15px;
	}

	.cate-spance-3 {
		display: inline-block;
		width: 30px;
	}

	.cat-line {
		display: inline-block;
		vertical-align: middle;
	}

	/deep/ .tree-table .tree-row,
	/deep/ .tree-table .tree-row.hover-row {
		.cell {
			overflow: visible !important;
		}
	}

	.ms-tree-space {
		position: relative;
		top: 1px;
		display: inline-block;
		font-style: normal;
		font-weight: 400;
		line-height: 1;
		height: 14px;

		&.space-1 {
			width: 0px;
		}

		&.space-2 {
			width: 38px;
		}

		&.space-3 {
			width: 120px;
		}

		&::before {
			content: ""
		}
	}

	.tree-ctrl {
		position: relative;
		cursor: pointer;
		color: #2196F3;
	}
</style>
